package com.example.hospital.service;

import com.example.hospital.common.PageResponse;
import com.example.hospital.domain.entity.*;
import com.example.hospital.mapper.*;
import org.springframework.stereotype.Service;

import java.time.LocalDate;
import java.util.List;

@Service
public class AdminService {
    private final AdminMapper adminMapper;
    private final DepartmentMapper departmentMapper;
    private final PositionMapper positionMapper;
    private final IndicatorCategoryMapper indicatorCategoryMapper;
    private final ExaminationIndicatorMapper examinationIndicatorMapper;
    private final ExamPackageMapper examPackageMapper;
    private final PackageItemMapper packageItemMapper;
    private final UserMapper userMapper;
    private final DoctorMapper doctorMapper;
    private final ExaminationOrderMapper orderMapper;
    private final DoctorScheduleMapper scheduleMapper;

    public AdminService(AdminMapper adminMapper, DepartmentMapper departmentMapper, PositionMapper positionMapper, IndicatorCategoryMapper indicatorCategoryMapper, ExaminationIndicatorMapper examinationIndicatorMapper, ExamPackageMapper examPackageMapper, PackageItemMapper packageItemMapper, UserMapper userMapper, DoctorMapper doctorMapper, ExaminationOrderMapper orderMapper, DoctorScheduleMapper scheduleMapper) {
        this.adminMapper = adminMapper;
        this.departmentMapper = departmentMapper;
        this.positionMapper = positionMapper;
        this.indicatorCategoryMapper = indicatorCategoryMapper;
        this.examinationIndicatorMapper = examinationIndicatorMapper;
        this.examPackageMapper = examPackageMapper;
        this.packageItemMapper = packageItemMapper;
        this.userMapper = userMapper;
        this.doctorMapper = doctorMapper;
        this.orderMapper = orderMapper;
        this.scheduleMapper = scheduleMapper;
    }
    /**
     * 管理员登录
     * @param username
     * @param password
     * @return
     */
    public Admin login(String username, String password) {
        Admin admin = adminMapper.findByUsername(username);
        if (admin == null) throw new IllegalArgumentException("管理员不存在");
        // 示例：未实现密码加密（可根据需要改造）
        if (!password.equals(admin.getPassword())) throw new IllegalArgumentException("密码错误");
        return admin;
    }
    /**
     * 更新管理员个人信息
     * @param admin
     * @return
     */
    public boolean updateAdminProfile(Admin admin) { return adminMapper.updateProfile(admin) > 0; }

    // Doctor
    /**
     * 创建医生
     * @param d
     * @return
     */
    public Doctor createDoctor(Doctor d) {
        if (d.getPhone() == null || d.getPhone().isEmpty()) {
            throw new IllegalArgumentException("手机号不能为空");
        }
        Doctor exists = doctorMapper.findByPhone(d.getPhone());
        if (exists != null) {
            throw new IllegalArgumentException("手机号已存在");
        }
        // 明文保存初始密码（按当前需求）
        doctorMapper.insert(d);
        return doctorMapper.findById(d.getDoctorId());
    }

    // Department
    /**
     * 创建部门
     * @param d
     * @return
     */
    public Department createDepartment(Department d) { departmentMapper.insert(d); return departmentMapper.findById(d.getDepartmentId()); }
    public boolean updateDepartment(Department d) { return departmentMapper.update(d) > 0; }
    public boolean deleteDepartment(Long id) { return departmentMapper.delete(id) > 0; }
    public PageResponse<Department> listDepartments(String name, int page, int size) {
        int offset = (page - 1) * size;
        List<Department> list = departmentMapper.list(name, size, offset);
        long total = departmentMapper.count(name);
        return PageResponse.of(total, page, size, list);
    }

    // Position
    /**
     * 创建职务
     * @param p
     * @return
     */
    public Position createPosition(Position p) { positionMapper.insert(p); return positionMapper.findById(p.getPositionId()); }
    public boolean updatePosition(Position p) { return positionMapper.update(p) > 0; }
    public boolean deletePosition(Long id) { return positionMapper.delete(id) > 0; }
    public PageResponse<Position> listPositions(String name, int page, int size) {
        int offset = (page - 1) * size;
        List<Position> list = positionMapper.list(name, size, offset);
        long total = positionMapper.count(name);
        return PageResponse.of(total, page, size, list);
    }

    // Indicator Category
    /**
     * 创建指标分类
     * @param c
     * @return
     */
    public IndicatorCategory createCategory(IndicatorCategory c) { indicatorCategoryMapper.insert(c); return indicatorCategoryMapper.findById(c.getCategoryId()); }
    public boolean updateCategory(IndicatorCategory c) { return indicatorCategoryMapper.update(c) > 0; }
    public boolean deleteCategory(Long id) { return indicatorCategoryMapper.delete(id) > 0; }
    public PageResponse<IndicatorCategory> listCategories(String name, int page, int size) {
        int offset = (page - 1) * size;
        List<IndicatorCategory> list = indicatorCategoryMapper.list(name, size, offset);
        long total = indicatorCategoryMapper.count(name);
        return PageResponse.of(total, page, size, list);
    }

    // Examination Indicator
    /**
     * 创建指标
     * @param i
     * @return
     */
    public ExaminationIndicator createIndicator(ExaminationIndicator i) { examinationIndicatorMapper.insert(i); return examinationIndicatorMapper.findById(i.getIndicatorId()); }
    public boolean updateIndicator(ExaminationIndicator i) { return examinationIndicatorMapper.update(i) > 0; }
    public boolean deleteIndicator(Long id) { return examinationIndicatorMapper.delete(id) > 0; }
    public PageResponse<ExaminationIndicator> listIndicators(String code, String name, Long categoryId, int page, int size) {
        int offset = (page - 1) * size;
        List<ExaminationIndicator> list = examinationIndicatorMapper.list(code, name, categoryId, size, offset);
        long total = examinationIndicatorMapper.count(code, name, categoryId);
        return PageResponse.of(total, page, size, list);
    }

    // Package
    /**
     * 创建套餐
     * @param p
     * @return
     */
    public ExamPackage createPackage(ExamPackage p) { examPackageMapper.insert(p); return examPackageMapper.findById(p.getPackageId()); }
    public boolean updatePackage(ExamPackage p) { return examPackageMapper.update(p) > 0; }
    public boolean deletePackage(Long id) { return examPackageMapper.delete(id) > 0; }
    public PageResponse<ExamPackage> listPackages(String name, int page, int size) {
        int offset = (page - 1) * size;
        List<ExamPackage> list = examPackageMapper.list(name, size, offset);
        long total = examPackageMapper.count(name);
        return PageResponse.of(total, page, size, list);
    }
    /**
     * 添加套餐项目
     * @param item
     * @return
     */
    public PackageItem addPackageItem(PackageItem item) {
        packageItemMapper.insert(item);
        return item;
    }
    /**
     * 删除套餐项目
     * @param id
     * @return
     */
    public boolean removePackageItem(Long id) {
        return packageItemMapper.delete(id) > 0;
    }
    /**
     * 获取套餐项目列表
     * @param packageId
     * @return
     */
    public List<PackageItem> listPackageItems(Long packageId) {
        return packageItemMapper.listByPackageId(packageId);
    }

    // View users/doctors/admins
    /**
     * 获取用户列表
     * @param name
     * @param phone
     * @param gender
     * @param page
     * @param size
     * @return
     */
    public PageResponse<User> listUsers(String name, String phone, String gender, int page, int size) {
        int offset = (page - 1) * size;
        List<User> list = userMapper.list(name, phone, gender, size, offset);
        long total = userMapper.count(name, phone, gender);
        return PageResponse.of(total, page, size, list);
    }
    /**
     * 获取医生列表
     * @param name
     * @param departmentId
     * @param positionId
     * @param page
     * @param size
     * @return
     */
    public PageResponse<Doctor> listDoctors(String name, Long departmentId, Long positionId, int page, int size) {
        int offset = (page - 1) * size;
        List<Doctor> list = doctorMapper.list(name, departmentId, positionId, size, offset);
        long total = doctorMapper.count(name, departmentId, positionId);
        return PageResponse.of(total, page, size, list);
    }
    /**
     * 获取管理员列表
     * @param name
     * @param page
     * @param size
     * @return
     */
    public PageResponse<Admin> listAdmins(String name, int page, int size) {
        int offset = (page - 1) * size;
        List<Admin> list = adminMapper.list(name, size, offset);
        long total = adminMapper.count(name);
        return PageResponse.of(total, page, size, list);
    }

    // Orders
    /**
     * 获取订单列表
     * @param userId
     * @param doctorId
     * @param status
     * @param orderType
     * @param page
     * @param size
     * @return
     */
    public PageResponse<ExaminationOrder> listOrders(Long userId, Long doctorId, Integer status, String orderType, int page, int size) {
        int offset = (page - 1) * size;
        List<ExaminationOrder> list = orderMapper.list(userId, doctorId, status, orderType, size, offset);
        long total = orderMapper.count(userId, doctorId, status, orderType);
        return PageResponse.of(total, page, size, list);
    }

    // Doctor schedules (admin manages)
    /**
     * 创建医生排班
     * @param s
     * @return
     */
    public DoctorSchedule createSchedule(DoctorSchedule s) { scheduleMapper.insert(s); return scheduleMapper.findById(s.getScheduleId()); }
    /**
     * 更新医生排班
     * @param s
     * @return
     */
    public boolean updateSchedule(DoctorSchedule s) {
        return scheduleMapper.update(s) > 0;
    }
    /**
     * 删除医生排班
     * @param id
     * @return
     */
    public boolean deleteSchedule(Long id) {
        return scheduleMapper.delete(id) > 0;
    }
    /**
     * 获取医生排班列表
     * @param doctorId
     * @param date
     * @param page
     * @param size
     * @return
     */
    public PageResponse<DoctorSchedule> listSchedules(Long doctorId, LocalDate date, int page, int size) {
        int offset = (page - 1) * size;
        List<DoctorSchedule> list = scheduleMapper.list(doctorId, date, size, offset);
        long total = scheduleMapper.count(doctorId, date);
        return PageResponse.of(total, page, size, list);
    }
}